#!/bin/bash
set -e

# Get the configuration and action parameters.
proxied_ip=$(config-get proxied_ip)
login_password=$(config-get password)
home_domain=$(config-get home_domain)
number=$(action-get number)
password=$(action-get password)

if [ -z "$proxied_ip" ] || [ -z "$login_password" ] || [ -z "$home_domain" ] ; then
  echo Proxy not yet configured!
  exit 1
fi

# If the user doesn't exist, try to create them.  Otherwise, try to update them.
if ! sshpass -p$login_password ssh -o StrictHostKeyChecking=no ubuntu@$proxied_ip "echo $login_password | sudo -S /usr/share/clearwater/bin/display_user $number $home_domain" ; then
  echo "Subscriber doesn't exist - creating"
  sshpass -p$login_password ssh -o StrictHostKeyChecking=no ubuntu@$proxied_ip "echo $login_password | sudo -S /usr/share/clearwater/bin/create_user $number $home_domain $password"
else
  echo "Subscriber exists - updating"
  sshpass -p$login_password ssh -o StrictHostKeyChecking=no ubuntu@$proxied_ip "echo $login_password | sudo -S /usr/share/clearwater/bin/update_user $number $home_domain --password $password"
fi
